const path = require('path');

function log(msg) {
  // eslint-disable-next-line no-console
  console.log('\n ====================== webpack info: ', msg, '====================== \n');
}
// 页面注册
const defaultPages = {};
const PAGES = [
  'index',
];

function creatEntryPage() {
  const page = {};
  function beIndex(pathName) {
    return pathName === 'index' ? 'src' : pathName;
  }
  PAGES.forEach((item) => {
    if (item === 'examples' && process.env.ENV_MODE_EXAMPLE !== 'true') {
      return false;
    }
    page[item] = {
      entry: `${beIndex(item)}/main.js`,
      template: `public/${item}.ejs`,
      filename: `${item}.html`,
      title: item,
      chunks: ['chunk-vendors', 'chunk-common', item],
    };
    return true;
  });
  return Object.assign(page, defaultPages);
}

function createHtmlPage(config) {
  function getConfig(page) {
    const headScripts = [];
    if (process.env.ENV_CHUNKS_VCONSOLE === 'true') {
      log('VConsole 模块已载入');
      headScripts.push({
        src: './js/vconsole.js',
        content: 'new VConsole();',
      });
    }
    return {
      chunks: ['chunk-vendors', 'chunk-common', page],
      title: page,
      template: `public/${page}.ejs`,
      headScripts,
    };
  }
  // dynamically add entries and `HtmlWebpackPlugin`'s for every page
  let pageConfig = [];
  PAGES.forEach((item) => {
    if (item === 'examples' && process.env.ENV_MODE_EXAMPLE !== 'true') {
      return false;
    }
    pageConfig.push(getConfig(item));
    return true;
  });
  config
    .plugin('HtmlWebpackPlugin')
    .use(require.resolve('html-webpack-plugin'), pageConfig);
}

module.exports = {
  // 临时策略 官方不推荐 详细见https://github.com/vuejs/vue-cli/issues/4948
  publicPath: process.env.NODE_ENV === 'production' ? '././' : '/',
  outputDir: process.env.MODE, // 打包时生成的生产环境构建文件的目录
  assetsDir: 'assets', // 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录
  pages: creatEntryPage(),
  configureWebpack: {
    externals: {
      'bn.js': 'bn.js',
    },
    performance: {
      hints: 'warning',
      // 入口起点的最大体积
      maxEntrypointSize: 50000000,
      // 生成文件的最大体积
      maxAssetSize: 30000000,
      // 只给出 js 文件的性能提示
      assetFilter(assetFilename) {
        return assetFilename.endsWith('.js');
      },
    },
  },
  chainWebpack: (config) => {
    // 页面入口配置
    createHtmlPage(config);
    // 全局方法引入
    config.plugin('ProvidePlugin')
      .use(require.resolve('webpack/lib/ProvidePlugin'), [{ utils: path.resolve(path.join(__dirname, '../', '/src/utils/index.js')) }]);
    config.resolve.alias
      .set('@styles', path.join(__dirname, '../', '/src/assets/styles'))
      .set('@assetsImgs', path.join(__dirname, '../', '/src/assets/imgs'));
  },
};
